package com.tech.view.frame;

import com.tech.event.CloseActionListener;
import com.tech.repository.entity.User;
import com.tech.repository.session.UserSession;
import com.tech.service.UserService;
import com.tech.service.impl.ServiceImplFactory;
import com.tech.util.LogProcessUtil;
import com.tech.view.common.ResourcesUtil;
import com.tech.view.component.button.LoginButton;
import com.tech.view.component.input.IconTextField;
import com.tech.view.component.label.LinkText;
import com.tech.view.panel.CurvesPanel;
import org.jdesktop.animation.transitions.ScreenTransition;
import org.jdesktop.animation.transitions.TransitionTarget;
import org.jdesktop.core.animation.timing.Animator;
import org.jdesktop.core.animation.timing.interpolators.AccelerationInterpolator;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.StackLayout;
import org.jdesktop.swingx.VerticalLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 登录、注册框架
 */
public class LoginFrame extends JXFrame implements TransitionTarget, ActionListener {
	private final static Logger LOG = LogProcessUtil.getLogger(LoginFrame.class.getName());
	public static int WIDTH = 430;
	public static int HEIGHT = 353;
	private FrameManager frameManager;
	private JPanel mainPanel;
	private JPanel contentPanel;
	private JPanel formPanel;
	private JPanel checkBoxPanel;
	private CurvesPanel curves;
	private String title;
	private BufferedImage icon;
	private UserService userService;

	private IconTextField accountField;
	private IconTextField passwordField;
	private IconTextField affirmField;
	private IconTextField emailField;
	private JCheckBox[] checkBoxes;
	private LoginButton loginButton;
	private LinkText linkText;
	// 当前是否是登录
	private boolean isLogin = true;
	private Component emptyStrut = Box.createVerticalStrut(18);

	// 监听器
	private ActionListener loginActionListener;

	private ScreenTransition transition;

	public LoginFrame() {
		this.frameManager = FrameManager.getInstance();
		initService();
		initComponents();
		setListeners();
		initView();
	}

	private void initService() {
		userService = ServiceImplFactory.getUserService();
	}

	private void initComponents() {
		mainPanel = new JPanel();
		checkBoxPanel = new JPanel();
		formPanel = new JPanel();
		contentPanel = new JPanel();
		curves = new CurvesPanel();
		title = "好读书";
		icon = ResourcesUtil.getImage(ResourcesUtil.Image.LOGO);

		accountField = new IconTextField(ResourcesUtil.getImage(ResourcesUtil.Image.USER_ICON),
				ResourcesUtil.getImage(ResourcesUtil.Image.BOTTOM_ARROW_ICON),
				"请输入用户名",
				false);
		passwordField = new IconTextField(ResourcesUtil.getImage(ResourcesUtil.Image.PASSWORD_ICON),
				ResourcesUtil.getImage(ResourcesUtil.Image.KEYBOARD_ICON),
				"请输入密码",
				true);
		affirmField = new IconTextField(ResourcesUtil.getImage(ResourcesUtil.Image.PASSWORD_ICON),
				ResourcesUtil.getImage(ResourcesUtil.Image.KEYBOARD_ICON),
				"确认密码",
				true);
		emailField = new IconTextField(ResourcesUtil.getImage(ResourcesUtil.Image.EMAIL_ICON),
				ResourcesUtil.getImage(ResourcesUtil.Image.KEYBOARD_ICON),
				"请输入邮箱",
				false);

		checkBoxes = new JCheckBox[]{new JCheckBox("自动登录"), new JCheckBox("记住密码"), new JCheckBox("找回密码")};

		loginButton = new LoginButton("登录");

		linkText = new LinkText("立即注册");
	}

	private void initView() {
		setResizable(false);
		setTitle(title);
		setIconImage(icon);
		// TODO 所有放到一个面板上
		// TODO 使用 GridBagLayout，不再为占满区域而操心，将组件大小交给布局管理器
		contentPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
		contentPanel.setLayout(null);
		getContentPane().add(mainPanel);
		mainPanel.setLayout(new StackLayout());

		// 获取输入框的宽度作为所有组件的宽度
		int panelWidth = accountField.getPreferredSize().width;

		// 复选框
		for (JCheckBox checkBox : checkBoxes) {
			checkBoxPanel.add(checkBox);
		}

		formPanel.setLayout(new VerticalLayout());
		formPanel.setBounds((WIDTH - panelWidth) / 2, 115, panelWidth, HEIGHT);
		formPanel.add(accountField);
		formPanel.add(passwordField);
		formPanel.add(checkBoxPanel);
		formPanel.add(emptyStrut);
		formPanel.add(loginButton);

		Dimension linkTextSize = linkText.getPreferredSize();
		linkText.setBounds(20, HEIGHT - 70, linkTextSize.width, linkTextSize.height);

		// 开始播放动画
		curves.startAnimation();
		// 动画过渡
		Animator animator = new Animator.Builder()
				.setInterpolator(new AccelerationInterpolator(0.2f, 0.2f))
				.setDuration(500, TimeUnit.MILLISECONDS)
				.build();
		transition = new ScreenTransition.Builder(formPanel, this)
				.setAnimator(animator)
				.build();

		contentPanel.add(formPanel);
		contentPanel.add(linkText);
		mainPanel.add(contentPanel, StackLayout.TOP);
		mainPanel.add(curves);

		pack();
	}

	@Override
	public void setupNextScreen() {
		if (isLogin) {
			// 登录切换到注册
			curves.setVisible(false);
			passwordField.clear();
			affirmField.clear();
			emailField.clear();
			loginButton.setText("立即注册");
			linkText.setText("立即登录");
			passwordField.hideRightButton();
			affirmField.hideRightButton();
			emailField.hideRightButton();
			// TODO 注册事件
			// loginButton.addActionListener();

			formPanel.remove(checkBoxPanel);

			formPanel.add(affirmField, 2);
			formPanel.add(emailField, 3);
		} else {
			// 注册切换到登录
			curves.setVisible(true);
			linkText.setText("立即注册");
			formPanel.remove(affirmField);
			formPanel.remove(emailField);
			passwordField.showRightButton();

			formPanel.add(checkBoxPanel, 3);
		}
		isLogin = !isLogin;
		mainPanel.revalidate();
	}

	private void setListeners() {
		// 登录事件/注册事件
		loginButton.addActionListener(this);

		linkText.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				transition.start();
			}
		});

		// 关闭事件
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				new CloseActionListener().actionPerformed(null);
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String username = accountField.getText();
		String password = new String(passwordField.getPassword());
		String email = emailField.getText();
		// TODO 把通知框换成玻璃面板显示三秒的消息框
		if ("".equals(username)) {
			JOptionPane.showConfirmDialog(frameManager.getCurrentFrame(), "请先输入用户名", "提示", JOptionPane.YES_NO_OPTION);
			return;
		}
		if (password.equals("")) {
			JOptionPane.showConfirmDialog(frameManager.getCurrentFrame(), "请先输入密码", "提示", JOptionPane.YES_NO_OPTION);
			return;
		}
		try {
			if (isLogin) { //登录
				User user = userService.login(username, password);
				if (user != null) {
					// 登录成功
					UserSession.user = user;
					// TODO 应该先显示加载动画，等待商品列表数据加载完毕(特别是图片资源)再显示首页
					// 通知管理器切换框架
					frameManager.switchFrame(new MainFrame());
				} else {
					// 登录失败
					JOptionPane.showConfirmDialog(frameManager.getCurrentFrame(), "该用户不存在", "提示", JOptionPane.YES_NO_OPTION);
				}
			} else { //注册
				User user = new User(null, username, password, email);
				if (userService.register(user) != null) {
					JOptionPane.showConfirmDialog(frameManager.getCurrentFrame(), "注册成功", "提示", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
					UserSession.user = user;
					frameManager.switchFrame(new MainFrame());
				} else {
					JOptionPane.showConfirmDialog(frameManager.getCurrentFrame(), "注册失败", "提示", JOptionPane.YES_NO_OPTION);
				}
			}
		} catch (Exception ex) {
			LOG.throwing(this.getClass().getName(), "authenticate(username, password, null)", ex);
		}
	}
}
